﻿using System.Collections.Generic;

namespace nhCore.Modbus
{
    /// <summary>
    /// 气象数据解析器类，即读寄存器解析，解析实时、历史数据
    /// </summary>
    public class WeatherAnalyzer : Analyzer
    {
        public WeatherAnalyzer()
        {
            Name = "气象数据解析器";
            Decoders = new List<Decoder>();
        }

        public override object Analysis(object o)
        {
            byte[] byts = o as byte[];
            FrameValid mb = new FrameValid(byts, true);
            if (!mb.IsValid || mb.Data== null)
            {
                return null;
            }
            int index;
            Weathers ws = new Weathers();
            ws.Address = mb.Address;

            foreach (Decoder d in Decoders)
            {
                Weather w = new Weather
                {
                    Config = d.Config,
                };

                index = w.Config.Index;

                w.Value = d.DeCode(mb);
                if (!string.IsNullOrWhiteSpace(w.Config.Display) || !string.IsNullOrWhiteSpace(w.Config.Unit))
                {
                    w.StrValue = w.Value.HasValue ? d.Convert(w.Value.Value) : "-";
                    w.StrValueUnit = w.Value.HasValue ? d.ConvertWeather(w.Value.Value) : "-";
                }//display、unit都为空为隐藏要素，不显示
                ws.AddValue(index, w);//时间为index为-1，传感器数据也可能为0
            }
            return ws;
        }
    }
}
